package data.join.com.utils;

import android.text.TextUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2017/9/18.
 */

public class FileUtils {
    public static final String DIR_APP = "/sdcard" + File.separator + "joinData";

    public static void deleteFile(String path){
        if(!TextUtils.isEmpty(path)){
            File f = new File(path);
            if(f.exists()) f.delete();
        }
    }


    public static boolean writeResponseBodyToDisk(ResponseBody body, String filePath) {
        try {
            File downloadFile = new File(filePath);

            if(downloadFile.exists()){
                downloadFile.delete();
            }

            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(downloadFile);

                while (true) {
                    int read = inputStream.read(fileReader);

                    if (read == -1) {
                        break;
                    }

                    outputStream.write(fileReader, 0, read);

                    fileSizeDownloaded += read;

                    MyLog.D( "file download: " + fileSizeDownloaded + " of " + fileSize);
                }

                outputStream.flush();

                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }

    public static String getFilePath(String ETag){
        String dir = DIR_APP;
        long time = System.currentTimeMillis();
        String path = dir + File.separator + ETag+"_"+time + ".bin";

        File dirFile = new File(dir);

        if(!dirFile.exists()){
            dirFile.mkdir();
        }

        return path;
    }

    public static long getFileSize(String filePath){
        long size = 0;
        try{
            size = new File(filePath).length();
        }catch (Exception e){
            e.printStackTrace();
        }

        return 0;
    }
}
